<template>
  <Dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    width="690px"
    :fullscreen="false"
    :scroll="true"
    maxHeight="450px"
  >
    <div class="upload-box" @click="openForm">
      <img src="@/assets/patient/knowledgeData/upload.png" class="upload-img" />
      <el-upload
        ref="uploadRef"
        v-model:file-list="fileList"
        :action="uploadUrl"
        :auto-upload="true"
        :data="data"
        :show-file-list="false"
        :disabled="formLoading"
        :limit="1"
        :on-change="handleFileChange"
        :on-error="submitFormError"
        :on-exceed="handleExceed"
        :on-success="submitFormSuccess"
        :http-request="httpRequest"
        accept="doc, docx, pdf"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text"> 点击上传</div>
      </el-upload>
      <span class="description">提示：仅允许导入doc、docx、pdf、格式文件！</span>
    </div>
    <div class="doc-box">
      <div class="left-box" v-for="(item, index) in fileList" :key="index">
        <img v-if="item.name.endsWith('.pdf')" src="@/assets/patient/knowledgeData/pdf-img.png" />
        <!-- <img
          v-if="item.type === 'jpg' || item.type === 'jpeg'"
          src="@/assets/patient/knowledgeData/picture-img.png"
        /> -->
        <img
          v-if="item.name.endsWith('.doc') || item.name.endsWith('.docx')"
          src="@/assets/patient/knowledgeData/word.png"
        />
        <span class="doc-text" :title="item.numberName">{{ item.name }}</span>
        <img
          src="@/assets/patient/knowledgeData/del-img.png"
          class="del-img"
          @click="deleteFile(item)"
        />
      </div>
    </div>
    <div class="input-box">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px" class="form-flex">
        <div class="input-left-box">
          <el-form-item label="名称" prop="name" class="custom-form-item1">
            <el-input v-model="form.name" />
          </el-form-item>
          <el-form-item label="实施日期" prop="execDate" class="custom-form-item1">
            <el-date-picker type="date" v-model="form.execDate" :clearable="true" />
          </el-form-item>
        </div>
        <div class="input-right-box">
          <el-form-item label="发布日期" prop="publishDate" class="custom-form-item1">
            <el-date-picker type="date" v-model="form.publishDate" :clearable="true" />
          </el-form-item>
          <el-form-item label="废止时间" prop="abortDate" class="custom-form-item3">
            <el-date-picker type="date" v-model="form.abortDate" :clearable="true" />
          </el-form-item>
        </div>
      </el-form>
    </div>
    <template #footer>
      <el-button type="primary" :disabled="formLoading" @click="submitFileForm">确 定</el-button>
      <el-button @click="handleClose">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import { ElMessage, FormInstance, FormRules } from 'element-plus'
import FileForm from './FileForm.vue'
import { useUpload } from '@/components/UploadFile/src/useUpload'
import * as KnowledgeDataApi from '@/api/patient/knowledgeData'
defineOptions({ name: 'KnowledgeDataAdd' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中
const fileList = ref([]) // 文件列表
const data = ref({ path: '' })
const uploadRef = ref()
const formRef = ref()
const form = ref({
  id: undefined,
  execDate: undefined,
  name: undefined,
  publishDate: undefined,
  abortDate: undefined
})

const rules = reactive<FormRules>({
  execDate: [{ required: false, message: '请选择实施日期', trigger: 'blur' }],
  name: [
    { required: true, message: '请输入名称', trigger: 'blur' },
    { max: 50, message: '名称长度不超过50个字符', trigger: 'blur' }
  ],
  publishDate: [{ required: true, message: '请选择发布日期', trigger: 'blur' }]
})

const { uploadUrl, httpRequest } = useUpload()

/** 处理上传的文件发生变化 */
const handleFileChange = (file) => {
  data.value.path = file.name
}

/** 提交表单 */
const submitFileForm = async () => {
  if (fileList.value.length == 0) {
    message.error('请上传文件')
    return
  }
  formRef.value?.validate((valid) => {
    if (valid) {
      const params = {
        id: form.value.id,
        name: form.value.name,
        publishDate: form.value.publishDate,
        execDate: form.value.execDate,
        abortDate: form.value.abortDate,
        textAttachmentUrl: fileList.value[0].response.data
      }
      if (!form.value.id) {
        //调用新增接口
        KnowledgeDataApi.addKnowledgeData(params).then((res) => {
          // 清理（基本信息成功后执行以下逻辑）
          dialogVisible.value = false
          formLoading.value = false
          unref(uploadRef)?.clearFiles()
          // 提示成功，并刷新
          message.success(t('common.createSuccess'))
          emit('success')
        })
      } else {
        //调更新文件基本信息接口
        KnowledgeDataApi.editKnowledgeData(params).then((res) => {
          // 清理（基本信息成功后执行以下逻辑）
          dialogVisible.value = false
          formLoading.value = false
          unref(uploadRef)?.clearFiles()
          // 提示成功，并刷新
          message.success(t('common.createSuccess'))
          emit('success')
        })
      }
    }
  })
  //文件上传不自动提交要用
  // unref(uploadRef)?.submit()
}

/** 文件上传成功处理 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitFormSuccess = () => {
  // // 清理（文件上传不自动提交要用）
  // dialogVisible.value = false
  // formLoading.value = false
  // unref(uploadRef)?.clearFiles()
  // // 提示成功，并刷新
  // message.success(t('common.createSuccess'))
  // emit('success')
}

/** 上传错误提示 */
const submitFormError = (): void => {
  message.error('上传失败，请您重新上传！')
  formLoading.value = false
}

/** 重置表单 */
const resetForm = () => {
  // 重置上传状态和文件
  formLoading.value = false
  uploadRef.value?.clearFiles()
}

/** 文件数超出提示 */
const handleExceed = (): void => {
  message.error('最多只能上传一个文件！')
}

/** 打开弹窗 */
const open = async (type: string, item: any) => {
  formRef.value?.resetFields()
  form.value = {
    id: undefined,
    execDate: undefined,
    numberName: undefined,
    publishDate: undefined,
    abortDate: undefined,
    type: undefined
  }
  fileList.value = []
  dialogVisible.value = true
  dialogTitle.value = t(type)
  if (item != null) {
    form.value = item
    fileList.value.push({
      name: item.name + item.textAttachmentUrl.substring(item.textAttachmentUrl.lastIndexOf('.')),
      response: {
        data: item.textAttachmentUrl
      }
    })
  }
}

const handleClose = () => {
  dialogVisible.value = false
}

const deleteFile = (item: any) => {
  const index = fileList.value.findIndex((file) => file === item)
  if (index !== -1) {
    fileList.value.splice(index, 1)
  } else {
    message.error('文件删除失败')
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗
</script>
<style lang="scss" scoped>
.el-descriptions {
  margin-top: 20px;
}
.cell-item {
  display: flex;
  align-items: center;
}
.margin-top {
  margin-top: 20px;
}
.upload-box {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 620px;
  height: 179px;
  background-color: #f4f7f9;
  border-radius: 10px;
  border: 2px dotted #c9ced1;
  margin-bottom: 10px;
  .upload-img {
    width: 65px;
    height: 73px;
  }
  .upload-text {
    margin-top: -9px;
    margin-bottom: 12px;
    text-decoration: underline;
    font-family: Microsoft YaHei;
    font-weight: 400;
    font-size: 18px;
    color: #1989fa;
    cursor: pointer;
  }
  .description {
    font-family: Microsoft YaHei;
    font-weight: 400;
    font-size: 16px;
    color: #999999;
  }
}
.doc-box {
  display: flex;
  align-items: center;
  width: 620px;
  height: 68px;
  background-color: #f4f7f9;
  border-radius: 5px;
  overflow-x: auto;
  .left-box {
    display: flex;
    align-items: center;
    margin-right: 40px;
    max-height: 68px;
    max-width: 160px;
  }
  .left-box:first-child {
    margin-left: 17px;
  }
  .right-box {
    display: flex;
    align-items: center;
  }
  .doc-text {
    height: 36px;
    line-height: 36px;
    font-family: Microsoft YaHei;
    font-weight: 400;
    font-size: 14px;
    color: #1989fa;
    cursor: pointer;
    margin-left: 9px;
    margin-right: 8px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  .del-img {
    cursor: pointer;
  }
}
.input-box {
  display: flex;
  width: 100%;
  height: 188px;
  border-bottom: 1px solid #e6e6e6;
  .form-flex {
    display: flex;
    justify-content: space-between;
    width: 100%;
  }
  .input-left-box,
  .input-right-box {
    width: 310px;
    height: 100%;
    .custom-form-item1 {
      margin-top: 20px;
    }
    .custom-form-item3 {
      margin-bottom: 10px;
    }
  }
}
.footer {
  display: flex;
  justify-content: center;
  align-items: flex-end;
  width: 100%;
  height: 74px;
}
::v-deep .el-dialog__header {
  padding: 0;
  margin-bottom: 23px;
}
::v-deep .el-dialog__title {
  font-family: Microsoft YaHei;
  font-weight: bold;
  font-size: 24px;
  color: #333333;
}
::v-deep .el-dialog__body {
  padding: 0;
}
::v-deep .el-input {
  width: 198px;
}
::v-deep .el-button.form-button {
  width: 120px;
  height: 44px;
  font-size: 16px;
}
::v-deep .el-form-item__error {
  padding-top: 1px;
}
</style>
